var editor = null;
var editor2 = null;
$(function(){
	editor = new wangEditor('editor');
	editor.config.uploadImgUrl='/admin/editorFile';
	editor.config.uploadImgFileName='uploadFile';
	//取消地图插件
	editor.config.menus = $.map(wangEditor.config.menus, function(item, key) {if (item === 'location') {return null;}return item;});
	editor.create();
	
	editor2 = new wangEditor('editor2');
	editor2.config.uploadImgUrl='/admin/editorFile';
	editor2.config.uploadImgFileName='uploadFile';
	editor2.config.menus = $.map(wangEditor.config.menus, function(item, key) {if (item === 'location') {return null;}return item;});
	editor2.create();
	$('#editor').css('height',400);
	$('#editor2').css('height',400);
 	//初始化编辑器
	$('.hide-div').hide();
    $('.selectPhoto').click(function(){
    	$('.input-file').click();
    });
  	//Date picker
    $('#datepicker').datepicker({
      autoclose: true
    });
    $('#datepickerEdit').datepicker({
    	autoclose: true
    });
    $(".edit-article").on('click',function(){
    	updateArticle()
    });
})
//文章发布
function saveArticle(){
	var content = editor.$txt.html();
    var photo = $('.form-article-add[name="photo"]').val();
	var category = $(".form-article-add[name='category']").val();
	var order = $(".form-article-add[name='order']").val();
	var author = $('.form-article-add[name="author"]').val();
	var title = $('.form-article-add[name="title"]').val();
	var date = $(".form-article-add[name='date']").val();
	if(date==''){
		date = new Date();
	}
	var boola = isEmpty(content,'内容不得为空');
	var boolb = isEmpty(title,'标题不得为空');
	if(boola||boolb){
		$.notify("标题或内容不得为空", {
			position : 'top center',
			className : 'error'
		});
		return ;
	}
	$.ajax({
		url:'/admin/article',
		type:'post',
		data:{
			content:content,
			photo:photo,
			title:title,
			order:order,
			author:author,
			date:date,
			'category.id':category,
		},
		success:function(data){
			if(data=='success'){
				$.notify("发布文章成功!", {
					position : 'top center',
					className : 'success'
				});
			}
		}
	});
}
$('.save-article').click(saveArticle);

    $.ajax({
    	url:'/articleCategoryList',
    	type:'get',
    	success:function(data){
    		var categoryList = eval(data);
    		var $select = $("#articleCategorySelect"); 
    		var $select2 = $("#articleCategoryEditSelect"); 
    		for(var i=0;i<categoryList.length;i++){
    			var category = categoryList[i];
    			$select.append('<option value="'+category.id+'">'+category.name+'</option>');
    			$select2.append('<option value="'+category.id+'">'+category.name+'</option>');
    		}
    	}
    });
    
    function uploadPhoto(){
    	var formData = new FormData($('.photoUpladForm')[0]);
    	$.ajax({
    		url:'/admin/file',
    		type:'post',
    		data:formData,
    		contentType: false,
    	    processData: false,
    		success:function(data){
    			if(data.msg=='ok'){
	    			var url = data.data;
	    			$('.articlePhotoImg').attr('src',url);
	    			$('.articlePhoto').val(url);    				
    			}
    		}
    	});
    }
    
    //====================
    var $table = $('#articleTable');
	function initTable() {
		//先销毁表格  
		$table.bootstrapTable('destroy');
		//初始化表格,动态从服务器加载数据  
		$table.bootstrapTable({
			method : "get", //使用get请求到服务器获取数据  
			url : "/articles", //获取数据的Servlet地址  
			method : 'get', //请求方式（*）
			queryParams:function(){
				return {
					order:'desc'
				}
			},
			toolbar : '#toolbar', //工具按钮用哪个容器
			striped : true, //是否显示行间隔色
			cache : false, //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
			pagination : true, //是否显示分页（*）
			sortable : true, //是否启用排序
			sortOrder : "asc", //排序方式
			//queryParams: queryParams,//传递参数（*）
			sidePagination : "server", //分页方式：client客户端分页，server服务端分页（*）
			pageNumber : 1, //初始化加载第一页，默认第一页
			pageSize : 10, //每页的记录行数（*）
			pageList : [ 10, 25, 50, 100 ], //可供选择的每页的行数（*）
			strictSearch : true,
			clickToSelect : true, //是否启用点击选中行
			//height: 460,                        //行高，如果没有设置height属性，表格自动根据记录条数觉得表格高度
			uniqueId : "id", //每一行的唯一标识，一般为主键列
			cardView : false, //是否显示详细视图
			detailView : false, //是否显示父子表
			onLoadSuccess:function(){
				var $select = $(".editable-order-select");
				for(var i=0;i<$select.size();i++){
					var $orderSelcct = $($select[i]);
					var value = $orderSelcct.attr("data-val");
					loadOrder($orderSelcct,value);
				}
			},
			columns : [
					{
						field : 'id',
						title : '序号'
					},
					{
						field : 'title',
						title : '标题',
					},
					{
						field:'author',
						title:'作者',
					},
					
					{
						field:'category',
						title:'栏目',
						formatter:function(value, row, index){
							if(value!=null&&value.name){
								return [value.name ].join('');							
							}
							return "无";
						}
					},{
						field:'order',
						title:'置顶',
						formatter:function(value, row, index){
							return [
								'<select name="order" class="form-control editable-order-select" onchange="updateOrder(this',',',row.id,')" data-val="',value,'">',
			                  	'<option value="5" >普通</option>',
			                  	'<option value="4">置顶1</option>',
			                  	'<option value="3">置顶2</option>',
			                  	'<option value="2">置顶3</option>',
			                  	'<option value="6">置后1</option>',
			                  	'<option value="7">置后2</option>',
			                  	'<option value="8">置后3</option>',
			                 ' </select>',
							].join('');							
		
						}
					},
					{
						field:'date',
						title:'日期',
					},{
						field:'photo',
						title:'图片',
						
						formatter:function(value, row, index){
							return [ '<img src="',value,'" style="max-height:50px;max-width:50px"/>'].join('');
						}
					},
					{
						field : 'operate',
						title : 'Item Operate',
						align : 'center',
						events : {
							'click .edit' : function(e, value, row, index) {
								var id = row.id;
								editArticleModal(id);
							},
							'click .remove' : function(e, value, row, index) {
								$.ajax({
									url : '/admin/article',
									type : 'post',
									data : {
										id : row.id,
										_method : 'delete'
									},
									success : function(data) {
										$.notify("删除成功", {
											position : 'top center',
											className : 'success'
										});
										$table.bootstrapTable('remove', {
											field : 'id',
											values : [ row.id ]
										});
									},
									error : function() {
										$.notify("删除失败", {
											position : 'top center',
											className : 'error'
										});
									}
								})

							}
						},
						formatter : operateFormatter
					} ]
		});
	}
	queryParams = function(params) {
		var temp = { //这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
			limit : params.limit, //页面大小
			offset : params.offset, //页码
			sdate : $("#stratTime").val(),
			edate : $("#endTime").val(),
			sellerid : $("#sellerid").val(),
			orderid : $("#orderid").val(),
			CardNumber : $("#CardNumber").val(),
			maxrows : params.limit,
			pageindex : params.pageNumber,
			portid : $("#portid").val(),
			CardNumber : $("#CardNumber").val(),
			tradetype : $('input:radio[name="tradetype"]:checked').val(),
			success : $('input:radio[name="success"]:checked').val(),
		};
		return temp;
	};
	$(document).ready(function() {
		//调用函数，初始化表格  
		initTable();

		//当点击查询按钮的时候执行  
		$("#search").bind("click", initTable);
	});

	function operateFormatter(value, row, index) {
		return [ '<a class="edit" href="javascript:void(0)" title="Edit">',
				'<i class="glyphicon glyphicon-edit"></i>', '</a>  ',
				'<a class="remove" href="javascript:void(0)" title="Remove">',
				'<i class="glyphicon glyphicon-remove"></i>', '</a>' ].join('');
	}
	function loadOrder($select,value){
		$select.val(value);
	}
	
	function editArticleModal(id){
		//获取数据
		$.ajax({
			url:'/article/'+id,
			type:'get',
			data:{
				id:id
			},
			success:function(data){
				//将数据设置到模块
				editor2.$txt.html(data.content);
			    $('.form-article-edit[name="photo"]').val(data.photo);
			    $('.form-article-edit[name="id"]').val(data.id);
			    if(null!=data.category){
			    	$(".form-article-edit[name='category']").val(data.category.id);			    	
			    }
				$(".form-article-edit[name='order']").val(data.order);
				$('.form-article-edit[name="author"]').val(data.author);
				$('.form-article-edit[name="title"]').val(data.title);
				$(".form-article-edit[name='date']").val(data.date);
				$(".articleEditPhotoImg").attr('src',data.photo)
				
			}
		})
		//更新模块
		
		$('#myModal').modal();
	}
	
	/**
	 * 编辑文章
	 * @returns
	 */
	function updateArticle(){
		//获取数据
		var id = $('.form-article-edit[name="id"]').val();
		if(!id){
			$.notify("无标识符，无法编辑", {
				position : 'top center',
				className : 'error'
			});
			return ;
		}
		var content = editor2.$txt.html();
	    var photo = $('.form-article-edit[name="photo"]').val();
		var category = $(".form-article-edit[name='category']").val();
		var order = $(".form-article-edit[name='order']").val();
		var author = $('.form-article-edit[name="author"]').val();
		var title = $('.form-article-edit[name="title"]').val();
		var date = $(".form-article-edit[name='date']").val();

		if(!date){
			date=new Date();
		}
		$.ajax({
			url:'/admin/article',
			type:'post',
			data:{
				_method:'put',
				id:id,
				content:content,
				photo:photo,
				'category.id':category,
				order:order,
				author:author,
				title:title,
				date:new Date(date),
			},
			success:function(data){
				if(data!="success"){
					$.notify("编辑失败", {
						position : 'top center',
						className : 'error'
					});
					return ;
				}
				$.notify("编辑成功", {
					position : 'top center',
					className : 'success'
				});
				//关闭模块
				$('.edit-modal-close').click();
				//刷新列表
				$('.article-table').bootstrapTable('refresh');
			}
		})
	}